/// <summary>
/// 肌肉电刺激器的控制代码
/// </summary>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class muscleStimulator : MonoBehaviour
{
    public enum MC_COMMAND
    {
        MC_On,
        MC_Off,
        MC_execute,
        MC_stop,
        MC_reset,
        MC_increaseStrength,
        MC_decreaseStrength,
    }
    public enum MOTION
    {
        RAISE_ARM,
        DROP_ARM,
    }
    /// <summary>
    /// 肌肉控制器的实时状态
    /// </summary>
    enum MUSCLE_CONTROL_STATE
    {
        ///关闭状态
        MUSCLE_CONTROL_STATE_OFF = 0,
        ///正在开启状态
        MUSCLE_CONTROL_STATE_ON,
        ///空闲状态
        MUSCLE_CONTROL_STATE_IDLE,
        ///正在执行
        MUSCLE_CONTROL_STATE_EXECUTING,
        ///正在初始化
        MUSCLE_CONTROL_STATE_RESETTING,
        ///正在改变刺激强度
        MUSCLE_CONTROL_STATE_CHANGING
    };
    public serial serial;
    private MUSCLE_CONTROL_STATE state;
    // Start is called before the first frame update
    void Start()
    {
        //serial = gameObject.GetComponent<serial>();
        InvokeRepeating("stateUpdater", 1, 0.5f);
    }
    private void stateUpdater()
    {
        serial.sendString("MC_printState");
    }
    // Update is called once per frame
    // void Update()
    // {

    // }
    /// <summary>
    /// 发送指令
    /// </summary>
    /// <param name="command"></param>
    public void sendCommand(MC_COMMAND command)
    {
        try
        {
            if (serial.getSensorConnection() == serial.SENSOR_CONNECTION.OK)
                serial.sendString(command.ToString());
            else
            {
                Debug.Log("sersor not connect");
            }
        }
        catch (System.Exception e)
        {

            Debug.Log(e);
        }
    }
    /// <summary>
    /// 执行动作
    /// </summary>
    /// <param name="motion"></param>
    public void DoMotion(MOTION motion)
    {
        switch (motion)
        {
            case MOTION.RAISE_ARM:
                sendCommand(MC_COMMAND.MC_execute);
                break;
            case MOTION.DROP_ARM:
                sendCommand(MC_COMMAND.MC_stop);
                break;

        }
    }
    /// <summary>
    /// 解析下位机发送过来的字符串的处理函数，根据此来更新电刺激器的状态
    /// </summary>
    /// <param name="s"></param>
    public void analysisString(string s)
    {
        if (s.Contains("MC_STATE:"))
        {
            string[] args = s.Split(new char[2] { ':', ';' });
            Debug.Log("MC state:" + args[1]);
            state = (MUSCLE_CONTROL_STATE)int.Parse(args[1]);

        }
    }
}
